package com.yjw.demo.pattern.observer.mouse.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 监听器，它就是观察者的桥梁
 */
public class EventListener {

    // JDK 底层的Listener通常也是这样设计的
    private Map<String, Event> events = new HashMap<>();

    /**
     * 添加事件监听
     *
     * @param eventType
     * @param target
     */
    public void addListener(String eventType, Object target) {
        try {
            this.addListener(eventType, target,
                    target.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void addListener(String eventType, Object target, Method callback) {
        // 注册事件
        events.put(eventType, new Event(target, callback));
    }

    /**
     * 触发事件
     *
     * @param event
     */
    public void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        try {
            // 发起回调
            if (event.getCallback() != null) {
                event.getCallback().invoke(event.getTarget(), event);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 触发事件
     *
     * @param trigger
     */
    protected void trigger(String trigger) {
        if (!this.events.containsKey((trigger))) {
            return;
        }
        trigger(this.events.get(trigger).setTrigger(trigger));
    }

    private String toUpperFirstCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }

}